﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Web.Configuration;
using System.Data;
using System.Diagnostics;
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Security.Principal;

using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Web.Security;



namespace doris.Agent {
    public partial class Ticket : System.Web.UI.Page {
        IPrincipal currentUser = HttpContext.Current.User;
        protected void Page_Load(object sender, EventArgs e) {
            if (Request.QueryString["id"] == null) {
                Response.Redirect("/Agent/Default.aspx");
            }
            
            if (Request.QueryString["action"] != null) {
               
                switch (Request.QueryString["action"]) {
                    case "responsible":
                        AssignToMe();
                        break;
                    case "removeResponsible":
                        MakeLock(false);
                        RemoveFromMe();
                        break;
                    case "lock":
                        MakeLock(true);
                        break;
                    case "removeLock":
                        MakeLock(false);
                        break;
                }
            }
            
            if (Request.QueryString["id"] != null) {
                if (AmIResponsible()) {
                    takeCase.NavigateUrl = "/Agent/Ticket.aspx?id=" + Request.QueryString["id"] + "&action=removeResponsible";
                    takeCase.Text = "Fjern ansvar";
                    lnkReply.Visible = true;
                    lLock.Visible = true;
                    int haveLock = DoIHaveLock();
                    Debug.WriteLine("lock: " + haveLock);
                    if (haveLock == 2) {
                        lLock.NavigateUrl = "/Agent/Ticket.aspx?id=" + Request.QueryString["id"] + "&action=removeLock";
                        lLock.Text = "Fjern l&aring;s";
                    } else if (haveLock == 0) {
                        lLock.NavigateUrl = "/Agent/Ticket.aspx?id=" + Request.QueryString["id"] + "&action=lock";
                    }
                } else {
                    takeCase.NavigateUrl = "/Agent/Ticket.aspx?id=" + Request.QueryString["id"] + "&action=responsible";
                    lnkReply.Visible = false;
                    lLock.Visible = false;
                }
            }

            if (Request.QueryString["d"] != null) {
                LiteralControl objMessage = Message.Controls[0] as LiteralControl;
                /*
                IPrincipal currentUser = HttpContext.Current.User; 
                bool writeEnable = currentUser.IsInRole("Administrator") 
                bool blabla = currentUser.IsInRole("Operator");
                */
                //                HttpContext.Current.User.Identity.Name;

                MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
                try {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    cmd.CommandText = "getTicketDataByID";
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add(new MySqlParameter("@in_ticketdataid", MySqlDbType.Int32));
                    cmd.Parameters["@in_ticketdataid"].Value = int.Parse(Request.QueryString["d"]);
                    cmd.Parameters["@in_ticketdataid"].Direction = ParameterDirection.Input;

                    cmd.Parameters.Add(new MySqlParameter("@out_ticketid", MySqlDbType.Int32));
                    cmd.Parameters["@out_ticketid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_createddate", MySqlDbType.DateTime));
                    cmd.Parameters["@out_createddate"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_updateddate", MySqlDbType.DateTime));
                    cmd.Parameters["@out_updateddate"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_title", MySqlDbType.VarChar));
                    cmd.Parameters["@out_title"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_message", MySqlDbType.Text));
                    cmd.Parameters["@out_message"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_ticketdatatypeid", MySqlDbType.Int32));
                    cmd.Parameters["@out_ticketdatatypeid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_type", MySqlDbType.VarChar));
                    cmd.Parameters["@out_type"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_workminutes", MySqlDbType.VarChar));
                    cmd.Parameters["@out_workminutes"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_agentid", MySqlDbType.VarChar));
                    cmd.Parameters["@out_agentid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_tickedassignedid", MySqlDbType.Int32));
                    cmd.Parameters["@out_tickedassignedid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_parentticketdataid", MySqlDbType.Int32));
                    cmd.Parameters["@out_parentticketdataid"].Direction = ParameterDirection.Output;
                    
                    cmd.ExecuteNonQuery();

                    objMessage.Text = "<pre>" + cmd.Parameters["@out_message"].Value.ToString() + "</pre>";

                    lnkReply.NavigateUrl = "Reply.aspx?id=" + Request.QueryString["id"] + "&d=" + Request.QueryString["d"];
                    cmd.Dispose();
                } catch (MySql.Data.MySqlClient.MySqlException ex) {
                    Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
                } finally {
                    conn.Close();
                }
            } else if (Request.QueryString["id"] != null) {
                LiteralControl objMessage = Message.Controls[0] as LiteralControl;
                MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
                try {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    cmd.CommandText = "getTicketDataByTicketID";
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add(new MySqlParameter("@in_ticketid", MySqlDbType.Int32));
                    cmd.Parameters["@in_ticketid"].Value = int.Parse(Request.QueryString["id"]);
                    cmd.Parameters["@in_ticketid"].Direction = ParameterDirection.Input;

                    cmd.Parameters.Add(new MySqlParameter("@out_ticketdataid", MySqlDbType.Int32));
                    cmd.Parameters["@out_ticketdataid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_createddate", MySqlDbType.DateTime));
                    cmd.Parameters["@out_createddate"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_updateddate", MySqlDbType.DateTime));
                    cmd.Parameters["@out_updateddate"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_title", MySqlDbType.VarChar));
                    cmd.Parameters["@out_title"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_message", MySqlDbType.Text));
                    cmd.Parameters["@out_message"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_ticketdatatypeid", MySqlDbType.Int32));
                    cmd.Parameters["@out_ticketdatatypeid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_type", MySqlDbType.VarChar));
                    cmd.Parameters["@out_type"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_workminutes", MySqlDbType.VarChar));
                    cmd.Parameters["@out_workminutes"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_agentid", MySqlDbType.Int32));
                    cmd.Parameters["@out_agentid"].Direction = ParameterDirection.Output;
                    Debug.WriteLine("2");

                    cmd.Parameters.Add(new MySqlParameter("@out_tickedassignedid", MySqlDbType.Int32));
                    cmd.Parameters["@out_tickedassignedid"].Direction = ParameterDirection.Output;

                    cmd.Parameters.Add(new MySqlParameter("@out_parentticketdataid", MySqlDbType.Int32));
                    cmd.Parameters["@out_parentticketdataid"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    objMessage.Text = "<pre>" + cmd.Parameters["@out_message"].Value.ToString() + "</pre>";

                    lnkReply.NavigateUrl = "Reply.aspx?id=" + Request.QueryString["id"] + "&d=" + cmd.Parameters["@out_ticketdataid"].Value.ToString();
                    cmd.Dispose();
                } catch (MySql.Data.MySqlClient.MySqlException ex) {
                    Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
                } finally {
                    conn.Close();
                }
            } else {
                lnkReply.Visible = false;
            }
        }

        protected int DoIHaveLock() {
            int locked = 0;
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "getLockForTicket";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_ticketid", MySqlDbType.Int32));
                cmd.Parameters["@in_ticketid"].Value = int.Parse(Request.QueryString["id"]);
                cmd.Parameters["@in_ticketid"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@out_locked", MySqlDbType.Int16));
                cmd.Parameters["@out_locked"].Direction = ParameterDirection.Output;

                cmd.Parameters.Add(new MySqlParameter("@out_lockedbyusername", MySqlDbType.VarChar));
                cmd.Parameters["@out_lockedbyusername"].Direction = ParameterDirection.Output;

                cmd.ExecuteNonQuery();

                if (cmd.Parameters["@out_locked"].Value != null) {
                    if (String.Equals(cmd.Parameters["@out_lockedbyusername"].Value, currentUser.Identity.Name) && (int.Parse(cmd.Parameters["@out_locked"].Value.ToString()) == 1)) {
                        locked = 2;
                    } else if (cmd.Parameters["@out_locked"].Value.ToString() != "" && int.Parse(cmd.Parameters["@out_locked"].Value.ToString()) == 1) {
                        locked = 1;
                    } else {
                        locked = 0;
                    }
                } 
                  

                //                cmd.Parameters["@out_locked"].Value 

                //                lnkReply.NavigateUrl = "Reply.aspx?id=" + Request.QueryString["id"] + "&d=" + Request.QueryString["d"];
                cmd.Dispose();
            } catch (MySql.Data.MySqlClient.MySqlException ex) {
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            } finally {
                conn.Close();
            }
            return locked;
        }

        protected Boolean AmIResponsible() {
            Boolean responsible = false;
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "getResponsibleForTicket";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_ticketid", MySqlDbType.Int32));
                cmd.Parameters["@in_ticketid"].Value = int.Parse(Request.QueryString["id"]);
                cmd.Parameters["@in_ticketid"].Direction = ParameterDirection.Input;

                MySqlDataReader reader = cmd.ExecuteReader();

                   
                while (reader.Read()) {
                    if (String.Compare(reader["Username"].ToString(),currentUser.Identity.Name.ToString()) == 0)
                        responsible = true;
                }


                //                lnkReply.NavigateUrl = "Reply.aspx?id=" + Request.QueryString["id"] + "&d=" + Request.QueryString["d"];
                cmd.Dispose();
            } catch (MySql.Data.MySqlClient.MySqlException ex) {
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            } finally {
                conn.Close();
            }
            return responsible;
        }

        protected void MakeLock(Boolean bLock) {
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                string sql;
                DorisMembershipProvider provider = new DorisMembershipProvider();
                NameValueCollection config = new NameValueCollection();
                config.Add("name", "DorisMembershipProvider");
                config.Add("type", "DorisMembershipProvider");
                config.Add("applicationName", "/");
                config.Add("connectionStringName", "localConnectionString");

                provider.Initialize("DorisMembershipProvider", config);
                MembershipUser user = provider.GetUser(currentUser.Identity.Name, false);
                //Label1.Text = user.ProviderUserKey.ToString();
                if (bLock == true){
                    sql = "UPDATE ticket SET Locked='1', LockedByUserID=?UserID WHERE TicketID = ?TicketID";
                }
                else{
                    sql = "UPDATE ticket SET Locked='0', LockedByUserID=NULL WHERE TicketID = ?TicketID"; 
                }

                conn.Open();
                MySqlCommand cmd = new MySqlCommand(sql);
                cmd.Connection = conn;
                cmd.Parameters.Add("?TicketID", MySqlDbType.Int32).Value = int.Parse(Request.QueryString["id"]);
                cmd.Parameters.Add("?UserID", MySqlDbType.VarChar, 36).Value = user.ProviderUserKey.ToString();

                /*
                cmd.CommandText = "storeLock";
                cmd.CommandType = CommandType.StoredProcedure;
               
                cmd.Parameters.Add(new MySqlParameter("@in_ticketid", MySqlDbType.Int32));
                cmd.Parameters["@in_ticketid"].Value = int.Parse(Request.QueryString["id"]);
                cmd.Parameters["@in_ticketid"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_locked", MySqlDbType.VarChar));
                cmd.Parameters["@in_locked"].Value = (bLock)?1:0;
                cmd.Parameters["@in_locked"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_username", MySqlDbType.VarChar));
                cmd.Parameters["@in_username"].Value = currentUser.Identity.Name;
                cmd.Parameters["@in_username"].Direction = ParameterDirection.Input;
               
              */
                cmd.ExecuteNonQuery();
               
                //                lnkReply.NavigateUrl = "Reply.aspx?id=" + Request.QueryString["id"] + "&d=" + Request.QueryString["d"];
                cmd.Dispose();
            } catch (MySql.Data.MySqlClient.MySqlException ex) {
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
               // Label1.Text = "Error " + ex.Number + " has occurred: " + ex.Message;
               
            } finally {
                conn.Close();
            }
        }

        protected void AssignToMe() {
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "addTicketResponsible";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_ticketid", MySqlDbType.Int32));
                cmd.Parameters["@in_ticketid"].Value = int.Parse(Request.QueryString["id"]);
                cmd.Parameters["@in_ticketid"].Direction = ParameterDirection.Input;


                cmd.Parameters.Add(new MySqlParameter("@in_username", MySqlDbType.VarChar));
                cmd.Parameters["@in_username"].Value = currentUser.Identity.Name;
                cmd.Parameters["@in_username"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_priority", MySqlDbType.Int32));
                cmd.Parameters["@in_priority"].Value = 1;
                cmd.Parameters["@in_priority"].Direction = ParameterDirection.Input;

                cmd.ExecuteNonQuery();

//                lnkReply.NavigateUrl = "Reply.aspx?id=" + Request.QueryString["id"] + "&d=" + Request.QueryString["d"];
                cmd.Dispose();
            } catch (MySql.Data.MySqlClient.MySqlException ex) {
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            } finally {
                conn.Close();
            }
        }

        protected void RemoveFromMe() {
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "deleteTicketResponsible";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_ticketid", MySqlDbType.Int32));
                cmd.Parameters["@in_ticketid"].Value = int.Parse(Request.QueryString["id"]);
                cmd.Parameters["@in_ticketid"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_username", MySqlDbType.VarChar));
                cmd.Parameters["@in_username"].Value = currentUser.Identity.Name;
                cmd.Parameters["@in_username"].Direction = ParameterDirection.Input;

                cmd.ExecuteNonQuery();

                cmd.Dispose();
            } catch (MySql.Data.MySqlClient.MySqlException ex) {
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            } finally {
                conn.Close();
            }
        }
    }
}